<template>
  <div class="app-container">
    <el-card v-loading="loading">
      <!-- 返回按钮 -->
      <div style="margin-bottom: 16px;">
        <el-button @click="goBack" icon="ArrowLeft">返回列表</el-button>
      </div>

      <!-- 项目基本信息 -->
      <div class="item-header" style="margin-bottom: 24px;">
        <div style="display: flex; align-items: flex-start; gap: 24px;">
          <!-- 封面图片 -->
          <div class="item-image">
            <el-image
              v-if="itemInfo.imageUrl"
              :src="itemInfo.imageUrl"
              :preview-src-list="[itemInfo.imageUrl]"
              fit="cover"
              style="width: 300px; height: 200px; border-radius: 8px;"
              :preview-teleported="true"
            />
            <div v-else class="image-slot" style="width: 300px; height: 200px; border-radius: 8px; display: flex; flex-direction: column; justify-content: center; align-items: center; background: #f5f7fa; color: #909399;">
              <el-icon style="font-size: 30px;"><Picture /></el-icon>
              <div style="margin-top: 8px;">暂无封面图片</div>
            </div>
          </div>

          <!-- 基本信息 -->
          <div class="item-info" style="flex: 1;">
            <h1 style="font-size: 24px; font-weight: bold; margin-bottom: 16px;">{{ itemInfo.name }}</h1>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">项目分类：</span>
                <span class="value">{{ categoryName }}</span>
              </div>
              <div class="info-item">
                <span class="label">所属地区：</span>
                <span class="value">{{ regionName }}</span>
              </div>
              <div class="info-item">
                <span class="label">项目级别：</span>
                <el-tag :type="getLevelType(itemInfo.level)">{{ itemInfo.level }}</el-tag>
              </div>
              <div class="info-item">
                <span class="label">项目状态：</span>
                <el-tag :type="itemInfo.status === 1 ? 'success' : 'danger'">
                  {{ itemInfo.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">浏览量：</span>
                <span class="value">{{ itemDetail.viewCount || 0 }}</span>
              </div>
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ parseTime(itemInfo.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 详细介绍 -->
      <div class="section" style="margin-bottom: 24px;" v-if="itemDetail.description">
        <h2 class="section-title">详细介绍</h2>
        <div class="section-content">
          <div class="description-content" v-html="formatDescription(itemDetail.description)"></div>
        </div>
      </div>

      <!-- 相关图片 -->
      <div class="section" style="margin-bottom: 24px;" v-if="itemDetail.images && itemDetail.images.length > 0">
        <h2 class="section-title">相关图片</h2>
        <div class="section-content">
          <div class="image-gallery">
            <el-image
              v-for="(image, index) in itemDetail.images"
              :key="index"
              :src="image"
              :preview-src-list="itemDetail.images"
              :initial-index="index"
              fit="cover"
              class="gallery-image"
              :preview-teleported="true"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </div>
      </div>

      <!-- 相关视频 -->
      <div class="section" style="margin-bottom: 24px;" v-if="itemDetail.videos && itemDetail.videos.length > 0">
        <h2 class="section-title">相关视频</h2>
        <div class="section-content">
          <div class="video-gallery">
            <div v-for="(video, index) in itemDetail.videos" :key="index" class="video-item">
              <video :src="video" controls style="width: 100%; max-width: 400px; height: 225px;">
                您的浏览器不支持视频播放。
              </video>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="ItemDetail">
import { ref, onMounted, getCurrentInstance, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getItemDetail } from "@/api/management/item"
import { parseTime } from "@/utils/ruoyi"
import { Picture } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

const loading = ref(true)
const itemInfo = ref({})
const itemDetail = ref({})
const categoryName = ref('')
const regionName = ref('')

// 获取项目详情
const getDetail = async () => {
  try {
    loading.value = true
    const itemId = route.query.id
    console.log('获取到的路由参数 ID:', itemId)
    if (!itemId) {
      proxy.$modal.msgError('项目ID不能为空')
      goBack()
      return
    }
    
    console.log('开始请求项目详情，ID:', itemId)
    const response = await getItemDetail(itemId)
    console.log('API响应:', response)
    console.log('API响应数据结构:', JSON.stringify(response.data, null, 2))
    if (response.code === 200) {
      // 后端返回的是ItemDetailVO对象，所有字段都在同一层级
      console.log('原始API数据:', response.data)
      
      // 直接使用response.data作为项目信息，因为ItemDetailVO包含了所有需要的字段
      itemInfo.value = response.data
      itemDetail.value = response.data  // 详情信息也在同一个对象中
      categoryName.value = response.data.categoryName || ''
      regionName.value = response.data.regionName || ''
      
      console.log('设置的数据:', {
        itemInfo: itemInfo.value,
        itemDetail: itemDetail.value,
        categoryName: categoryName.value,
        regionName: regionName.value,
        imageUrl: itemInfo.value.imageUrl
      })
      
      // 处理图片和视频字段 - ItemDetailVO中的images和videos已经是List类型
      // 如果后端返回的是字符串，则需要解析；如果已经是数组，则直接使用
      if (response.data.images) {
        if (typeof response.data.images === 'string') {
          try {
            itemDetail.value.images = JSON.parse(response.data.images)
          } catch (e) {
            // 如果解析失败，按照逗号分隔格式处理
            let imagesStr = response.data.images.trim()
            if (imagesStr.startsWith('"') && imagesStr.endsWith('"')) {
              imagesStr = imagesStr.slice(1, -1)
            }
            if (imagesStr) {
              itemDetail.value.images = imagesStr.split(',').map(url => url.trim()).filter(url => url)
            } else {
              itemDetail.value.images = []
            }
          }
        } else if (Array.isArray(response.data.images)) {
          itemDetail.value.images = response.data.images
        }
      }
      
      if (response.data.videos) {
        if (typeof response.data.videos === 'string') {
          try {
            itemDetail.value.videos = JSON.parse(response.data.videos)
          } catch (e) {
            // 如果解析失败，按照逗号分隔格式处理
            let videosStr = response.data.videos.trim()
            if (videosStr.startsWith('"') && videosStr.endsWith('"')) {
              videosStr = videosStr.slice(1, -1)
            }
            if (videosStr) {
              itemDetail.value.videos = videosStr.split(',').map(url => url.trim()).filter(url => url)
            } else {
              itemDetail.value.videos = []
            }
          }
        } else if (Array.isArray(response.data.videos)) {
          itemDetail.value.videos = response.data.videos
        }
      }
    }
  } catch (error) {
    console.error('获取项目详情失败:', error)
    proxy.$modal.msgError('获取项目详情失败')
  } finally {
    loading.value = false
  }
}

// 返回列表
const goBack = () => {
  router.go(-1) // 返回上一页
}

// 获取级别标签类型
const getLevelType = (level) => {
  switch (level) {
    case '国家级':
      return 'danger'
    case '省级':
      return 'warning'
    case '市级':
      return 'info'
    default:
      return ''
  }
}

// 格式化描述内容
const formatDescription = (description) => {
  if (!description) return ''
  // 简单的换行处理
  return description.replace(/\n/g, '<br>')
}

onMounted(() => {
  getDetail()
})

// 监听路由变化，当ID参数改变时重新获取数据
watch(() => route.query.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    console.log('路由ID变化:', oldId, '->', newId)
    getDetail()
  }
}, { immediate: false })
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.item-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 24px;
}

.item-info {
  padding-left: 24px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
}

.value {
  color: #303133;
}

.section {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
  display: inline-block;
}

.section-content {
  color: #606266;
  line-height: 1.6;
}

.description-content {
  font-size: 14px;
  line-height: 1.8;
}

.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.gallery-image {
  width: 100%;
  height: 150px;
  border-radius: 8px;
  cursor: pointer;
}

.video-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 16px;
}

.video-item {
  border-radius: 8px;
  overflow: hidden;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mb-6 {
  margin-bottom: 24px;
}

.flex {
  display: flex;
}

.items-start {
  align-items: flex-start;
}

.gap-6 {
  gap: 24px;
}

.flex-1 {
  flex: 1;
}

.text-2xl {
  font-size: 24px;
}

.font-bold {
  font-weight: 700;
}
</style>